import 'package:dio/dio.dart';

import 'package:flutter/material.dart';
import 'package:common_utils/common_utils.dart'; // 时间（第三方库）
import 'package:jiang_yue/buttonEffect/like_button.dart';
import 'package:jiang_yue/home/Toast.dart';
import 'package:jiang_yue/modal/Article.dart';
import 'package:jiang_yue/modal/Comment.dart';
import 'package:jiang_yue/modal/Tages.dart';
import 'package:jiang_yue/utils/HttpUtils.dart';
import 'package:jiang_yue/utils/cache/UserCache.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart'; // 上拉加载，下拉刷新组件
import 'dart:async'; //异步组件
import 'package:flutter/cupertino.dart'; // 上拉加载，下拉刷新组件
import 'package:flutter/rendering.dart'; // 上拉加载，下拉刷新组件
import 'package:jiang_yue/home/PostShow.dart';
import 'package:jiang_yue/modal/User.dart'; // 用户数据模型
import 'package:jiang_yue/buttonEffect/model.dart';

// 该组件生成ListView列表视图和实现刷新功能

class Refresh extends StatefulWidget {
  List articles;
  final callback;

  Refresh({Key key, this.articles, this.callback}) : super(key: key);

  @override
  _RefreshState createState() => _RefreshState();
}

class _RefreshState extends State<Refresh> {
  // 更改点赞状态（接口）
  Future _handlePostChangeLike(int userID, int articleID, bool isLike) async {
    Response response = await Dio().post("http://47.93.201.127:8080/jiangyue/like", data: {
      "userID": userID,
      "articleID": articleID,
      "like": isLike,
    });

    widget.callback(userID);
  }

  enterPostShow(int index) {
    if (userInfo.length == 0) {
      Navigator.push(
        context,
        new MaterialPageRoute(
            builder: (context) => new PostShow(
                  // TODO: 传递userID，articleID获取帖子具体内容
                  callback: _handlePostChangeLike,
                  articleID: widget.articles[index]['postID'],
                  index: index,
                )),
      );
      return;
    }

    Navigator.push(
      context,
      new MaterialPageRoute(
          builder: (context) => new PostShow(
                callback: _handlePostChangeLike,
                articleID: widget.articles[index]['postID'],
                index: index,
              )),
    );
  }

  Widget _listItemBuilder(BuildContext context, int index) {
    return Container(
      color: Colors.white,
      margin: EdgeInsets.all(8),
      child: Column(
        children: <Widget>[
          Stack(
            children: <Widget>[
              Column(
                children: <Widget>[
                  SizedBox(
                    height: 16,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Align(
                            child: Text(widget.articles[index]['postTitle'], style: TextStyle(fontSize: 20)),
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          Align(
                            child: Text(widget.articles[index]['author'], style: TextStyle(fontSize: 14)),
                          ),
                        ],
                      )
                    ],
                  ),
                  SizedBox(
                    height: 16,
                  ),
                  Container(
                    child: Text(
                      '${widget.articles[index]['content']}...',
                      maxLines: 3, // 数据对接时删去
                      overflow: TextOverflow.ellipsis, // 数据对接时删去
                    ),
                  ),
                  SizedBox(
                    height: 16,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: <Widget>[
                      Row(
                        children: <Widget>[
                          Text(
                            '类别： ',
                            style: TextStyle(color: Colors.grey, fontSize: 10),
                          ),
                          Container(
                            height: 35,
                            width: 60,
                            child: FittedBox(
                              fit: BoxFit.fill,
                              child: Chip(
                                avatar: getTag(widget.articles[index]['tagID']).icon,
                                label: getTag(widget.articles[index]['tagID']).content,
                              ),
                            ),
                          ),
                        ],
                      ),
                      SizedBox(
                        width: 30,
                      ),
                      Row(
                        children: <Widget>[
                          Text(
                            '结束时间：',
                            style: TextStyle(color: Colors.grey, fontSize: 10),
                          ),
                          Text('${DateUtil.getDateStrByMs(widget.articles[index]['lastTime'])}',
                              style: TextStyle(color: Colors.grey, fontSize: 10)),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
              Positioned.fill(
                child: Material(
                  color: Colors.transparent,
                  child: InkWell(
                      splashColor: Colors.grey.withOpacity(0.3),
                      highlightColor: Colors.grey.withOpacity(0.1),
                      onTap: () {
                        enterPostShow(index);
                      }),
                ),
              )
            ],
          ),
          SizedBox(
            height: 16,
          ),
          Divider(
            height: 2,
            color: Colors.grey[600],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              Row(
                children: <Widget>[
                  LikeButton(
                    width: 60.0,
                    circleStartColor: Color(0xff00ddff),
                    circleEndColor: Color(0xff0099cc),
                    dotColor: DotColor(
                      dotPrimaryColor: Color(0xff33b5e5),
                      dotSecondaryColor: Color(0xff0099cc),
                    ),
                    callback: _handlePostChangeLike,
                    isLiked: widget.articles[index]['like'],
                    index: index,
                    icon: LikeIcon(
                      Icons.thumb_up,
                      iconColor: Colors.red,
                    ),
                  ),
                  Text(
                    widget.articles[index]['likeNum'].toString(),
                    style: TextStyle(color: widget.articles[index]['like'] ? Colors.red : Colors.grey),
                  )
                ],
              ),
              Row(
                children: <Widget>[
                  IconButton(
                      icon: Icon(Icons.mode_comment, color: Colors.grey),
                      onPressed: () {
                        enterPostShow(index);
                      }),
                  Text(widget.articles[index]['commentNum'].toString(), style: TextStyle(color: Colors.grey))
                ],
              ),
              Row(
                children: <Widget>[
                  IconButton(
                    icon: Icon(Icons.share, color: Colors.grey),
                    onPressed: () {},
                  ),
                  Text(
                    '分享',
                    style: TextStyle(color: Colors.grey),
                  )
                ],
              ),
            ],
          )
        ],
      ),
    );
  }

  RefreshController _refreshController = RefreshController(initialRefresh: false);

  void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    _refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        header: ClassicHeader(
          height: 45.0,
          releaseText: '松开手刷新',
          refreshingText: '刷新中',
          completeText: '刷新完成',
          failedText: '刷新失败',
          idleText: '下拉刷新',
        ),
        footer: CustomFooter(
          builder: (BuildContext context, LoadStatus mode) {
            Widget body;
            if (mode == LoadStatus.idle) {
              body = Text("上拉加载");
            } else if (mode == LoadStatus.loading) {
              body = CupertinoActivityIndicator();
            } else if (mode == LoadStatus.failed) {
              body = Text("加载失败！点击重试！");
            } else if (mode == LoadStatus.canLoading) {
              body = Text("松手,加载更多!");
            } else {
              body = Text("没有更多数据了!");
            }
            return Container(
              height: 55.0,
              child: Center(child: body),
            );
          },
        ),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: ListView.builder(
          itemBuilder: _listItemBuilder,
          itemCount: widget.articles.length,
        ),
      ),
    );
  }
}
